//
//  ARWorkModel.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/6.
//

import Foundation

/// 作品模型
class ARWorkModel: Codable {
    
    var id: String = ""
    
    /// 标题
    var workTitle: String = ""
    /// 描述 - 内容
    var workDescription: String = ""
    /// 作者
    var authorId: String?
    var author: ARUserModel?
    /// 评论
    var comments: [ARCommentModel]? {
        didSet {
            self.setupCommentedAuthor()
        }
    }
    
    /// 已评论的用户 -> 排重
    var commentedAuthor: [ARUserModel]?
    
    /// 封面地址 - 只是名字
    var coverPath: String?
    /// 图片地址 - 只包含名字
    var picPaths: [String]?
    
    /// 本地图片地址
    var localCoverPath: String?
    var localPicPaths: [String]?
    
    /// 点赞数
    var likeNum: Int? = 0
    /// 当前用户是否喜欢
    var isLike: Bool? = false
        
    /// 是否审核中
    var isReview: Bool? = false
    
    static func picBundlePath(_ path: String) -> String? {
        /// 地址
        return Bundle.main.path(forResource: path, ofType: nil)
    }
    
    // MARK: - Codable
    
    enum CodingKeys: String, CodingKey {
        case workTitle, workDescription, likeNum, authorId, comments, coverPath, picPaths, localCoverPath, localPicPaths, isLike, id, isReview
    }
    
    // 重写方法
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        id = try container.decode(String.self, forKey: .id)
        workTitle = try container.decode(String.self, forKey: .workTitle)
        workDescription = try container.decode(String.self, forKey: .workDescription)
        likeNum = try container.decodeIfPresent(Int.self, forKey: .likeNum)
        isLike = try container.decodeIfPresent(Bool.self, forKey: .isLike)
        authorId = try container.decodeIfPresent(String.self, forKey: .authorId)
        comments = try container.decodeIfPresent([ARCommentModel].self, forKey: .comments)
        coverPath = try container.decodeIfPresent(String.self, forKey: .coverPath)
        picPaths = try container.decodeIfPresent([String].self, forKey: .picPaths)
        
        isReview = try container.decodeIfPresent(Bool.self, forKey: .isReview)
        
        if let path = try container.decodeIfPresent(String.self, forKey: .localCoverPath) {
            localCoverPath = "\(ARFileHelper.documentsDirectory)\(path)"
        }
        if let paths = try container.decodeIfPresent([String].self, forKey: .localPicPaths) {
            var array: [String] = []
            for path in paths {
                array.append(ARFileHelper.documentsDirectory+path)
            }
            localPicPaths = array
        }
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        
        try container.encodeIfPresent(id, forKey: .id)
        try container.encodeIfPresent(workTitle, forKey: .workTitle)
        try container.encodeIfPresent(workDescription, forKey: .workDescription)
        try container.encodeIfPresent(likeNum, forKey: .likeNum)
        try container.encodeIfPresent(authorId, forKey: .authorId)
        try container.encodeIfPresent(isLike, forKey: .isLike)
        try container.encodeIfPresent(comments, forKey: .comments)
        try container.encodeIfPresent(coverPath, forKey: .coverPath)
        try container.encodeIfPresent(picPaths, forKey: .picPaths)
        
        try container.encodeIfPresent(isReview, forKey: .isReview)
        
        if var localCoverPath = localCoverPath {
            // 替换
            localCoverPath = localCoverPath.replacingOccurrences(of: ARFileHelper.documentsDirectory, with: "")
            try container.encodeIfPresent(localCoverPath, forKey: .localCoverPath)
        }
        
        if let paths = localPicPaths {
            var array: [String] = []
            for path in paths {
                array.append(path.replacingOccurrences(of: ARFileHelper.documentsDirectory, with: ""))
            }
            try container.encode(array, forKey: .localPicPaths)
        }
    }
    
    init() {
        
    }
    
    // MARK: - Action
    
    func realPicsPath() -> [String]? {
        if let localPaths = localPicPaths {
            return localPaths
        }
        if let remotePaths = picPaths {
            return remotePaths
        }
        return nil
    }
    
    func realPicCover() -> String? {
        if let localCoverPath = localCoverPath {
            return localCoverPath
        }
        if let coverPath = coverPath {
            return coverPath
        }
        return nil
    }
    
    static func localImageFor(_ path: String) -> UIImage? {
        if path.contains(ARFileHelper.documentsDirectory) {
            // 本地
            return .init(contentsOfFile: path)
        }
        
        // bundle
        if let bundlePath = Self.picBundlePath(path) {
            return .init(contentsOfFile: bundlePath)
        }
        return nil
    }
    
    /// 设置评论的作者
    private func setupCommentedAuthor() {
        commentedAuthor = nil // 先置空
        guard let comments = comments else {
            return
        }
        
        var authors: [ARUserModel] = []
        // 记录id
        let idSet: NSMutableSet = .init()
        for comment in comments {
            guard let author = comment.author else {
                continue
            }
            if idSet.contains(author.userId) {
                continue
            }
            authors.append(author)
            idSet.add(author.userId)
        }
        commentedAuthor = authors
    }
    
    @objc func isCurrentUser() -> Bool {
        return authorId ?? "" == ARUserManager.shared.userId ?? ""
    }
}
